package com.lzlearn.springboothibernate.dao.impl;


import com.lzlearn.springboothibernate.dao.MyHibernateHqlDao;

import com.lzlearn.springboothibernate.model.User;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import java.util.List;


@Repository
public class HibernateHqlDaoImpl implements MyHibernateHqlDao {
    //通过注入将EntityManager注入到数据层
    @Resource
    private EntityManager entityManager;

    @Override
    public List<User> selectCondition(String name, Integer pageIndex, Integer pageCount) {
        Query query = entityManager.createQuery("select name from User where name like :name1");
        query.setParameter("name1","%"+name+"%");
        query.setFirstResult((pageIndex-1)*pageCount+1);
        query.setMaxResults(pageCount);
        List list = query.getResultList();
        return list;
    }
    //如果执行新增等需要事务管理的操作,需要 @Transactional注解打开事务管理
    @Transactional
    @Override
    public boolean updateUser(User user) {
        Query query = entityManager.createQuery("update User set name = :name,age = :age,email = :email where id = :id");
        query
            .setParameter("name",user.getName())
            .setParameter("age",user.getAge())
            .setParameter("email",user.getEmail())
            .setParameter("id",user.getId());
        int i = query.executeUpdate();
        if(i<=0){
            return false;
        }
       return true;
    }
    //因为会对数据库进行修改,所以事务管理必不可少
    @Transactional
    @Override
    public User selectAndUpdate(User user) {
        TypedQuery<User> query = entityManager.createQuery("select new User(id,name,age,email) from User where id =?1", User.class);
        query.setParameter(1,user.getId());
        User user1 = query.getSingleResult();
        return user1;
    }
}
